package com.smart.community.commons.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.smart.community.commons.config.sender.LogSender;
import com.smart.community.commons.config.sender.impl.LocalLogSender;
import com.smart.community.commons.config.sender.impl.RocketMQLogSender;

import lombok.extern.slf4j.Slf4j;

/**
 * 日志发送器配置类
 * 根据RocketMQ的可用性选择不同的日志发送器
 * @author Wu.Liang
 * @date 2025年1月20日
 * @updated 2025-01-30 - 添加条件配置，支持禁用RocketMQ功能
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "rocketmq.enabled", havingValue = "true", matchIfMissing = false)
public class LogSenderConfig {

	@Autowired
	private RocketMQLogSender rocketMQLogSender;
	
	@Autowired
	private LocalLogSender localLogSender;

	/**
	 * 主日志发送器
	 * 优先使用RocketMQ，如果不可用则使用本地日志
	 */
	@Bean
	@Primary
	public LogSender primaryLogSender() {
		return new LogSender() {
			@Override
			public void sendLog(com.smart.community.commons.dto.ApiLogDTO logDTO) {
				try {
					// 尝试使用RocketMQ发送
					rocketMQLogSender.sendLog(logDTO);
				} catch (Exception e) {
					log.warn("RocketMQ日志发送失败，切换到本地日志: {}", e.getMessage());
					// 如果RocketMQ失败，使用本地日志
					localLogSender.sendLog(logDTO);
				}
			}
		};
	}
}
